package com.caiwangdai.app.origin

import android.graphics.Rect
import android.view.View
import android.view.ViewTreeObserver

/**
 * @project KotLinProject
 * @author 艹羊
 * @date 2017/6/14 下午6:15
 * @description 监听软键盘启动关闭的基类
 */
abstract class KeyBoardObserverActivity : BaseActivity() {

    private var isShowInputBoard: Boolean = false////是否已经显示软键盘


    override fun onResume() {
        super.onResume()
        WMContent.viewTreeObserver.addOnGlobalLayoutListener(onGlobalFocusChangeListener)
    }


    override fun onPause() {
        super.onPause()
        WMContent.viewTreeObserver.removeOnGlobalLayoutListener(onGlobalFocusChangeListener)
    }

    /**
     * 监听软键盘
     */

    private val onGlobalFocusChangeListener: ViewTreeObserver.OnGlobalLayoutListener = ViewTreeObserver.OnGlobalLayoutListener() {
        WMContent.postDelayed({
            if (isKeyboardShown(WMContent)) {
                if (!isShowInputBoard) {
                    isShowInputBoard = true
                    onKeyBoardShow()
                }
            } else {
                if (isShowInputBoard) {
                    isShowInputBoard = false
                    onKeyBoardDismiss()
                }
            }
        }, 100)
    }


    //判断软键盘是否打开
    private fun isKeyboardShown(rootView: View): Boolean {
        val softKeyboardHeight = 100
        val r = Rect()
        rootView.getWindowVisibleDisplayFrame(r)
        val dm = rootView.resources.displayMetrics
        val heightDiff = rootView.bottom - r.bottom
        return heightDiff > softKeyboardHeight * dm.density
    }


    //软键盘显示
    abstract fun onKeyBoardShow()


    //软键盘隐藏
    abstract fun onKeyBoardDismiss()
}